package com.mz.mattress.admin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mz.mattress.admin.api.req.MemberCardQueryReq;
import com.mz.mattress.admin.api.req.MemberCardReq;
import com.mz.mattress.admin.api.resp.IntegerCount;
import com.mz.mattress.admin.api.resp.MerchantCardSum;
import com.mz.mattress.admin.mapper.CardMapper;
import com.mz.mattress.admin.mapper.CardMerchantMapper;
import com.mz.mattress.admin.mapper.MemberCardMapper;
import com.mz.mattress.admin.service.MemberCardService;
import com.mz.mattress.api.common.Result;
import com.mz.mattress.api.entity.Card;
import com.mz.mattress.api.entity.CardMerchant;
import com.mz.mattress.api.entity.MemberCard;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@Slf4j
public class MemberCardServiceImpl implements MemberCardService {

    @Autowired
    private CardMapper cardMapper;

    @Autowired
    private CardMerchantMapper cardMerchantMapper;

    @Autowired
    private MemberCardMapper memberCardMapper;

    @Override
    public Result<IPage<MemberCard>> listPage(MemberCardReq req) {
        Page<MemberCard> listPage = memberCardMapper.listPage(req.newPage(), req.getCardId(), req.getMerchantId(), req.getStatus());
        return Result.ok(listPage);
    }

    @Override
    public Result<IPage<MemberCard>> listAdminPage(MemberCardQueryReq req) {
        Page<MemberCard> listPage = memberCardMapper.listAdminPage(req.newPage(), req);
        return Result.ok(listPage);
    }

    @Override
    public Result<MemberCard> getById(Integer id) {

        MemberCard memberCard = memberCardMapper.selectById(id);

        Card card = cardMapper.selectById(memberCard.getCardId());
        memberCard.setRule(card.getRule());

        List<CardMerchant> list = cardMerchantMapper.selectByCardId(memberCard.getCardId());
        memberCard.setMerchantList(list);

        return Result.ok(memberCard);
    }

    @Override
    public Result<MerchantCardSum> selectSum(Integer merchantId, Integer cardId) {

        List<IntegerCount> list = memberCardMapper.selectSum(merchantId, cardId);

        MerchantCardSum sum = new MerchantCardSum();

        Integer total = 0;
        for (IntegerCount count : list) {
            total += count.getCount();
            //1已使用 2已过期
            if (count.getStatus() == 1) {
                sum.setChecked(count.getCount());
            } else if (count.getStatus() == 2) {
                sum.setExpired(count.getCount());
            }
        }
        sum.setTotal(total);

        return Result.ok(sum);
    }

}
